package com.tc.controller;

import com.tc.entity.RestApiController;
import com.tc.entity.UserInfo;
import com.tc.service.UserInfoSerivce;
import com.tc.utils.DataMask;
import com.tc.utils.RSAUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by cai.tian on 2017/5/8.
 */
@RestController
@RequestMapping("/user")
public class UserInfoAjax {

    @Autowired
    private UserInfoSerivce userInfoSerivce;

    @ResponseBody
    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public List<UserInfo> find(String loginName) {
        UserInfo u = new UserInfo();
        if (loginName == null || loginName == "") {
            u = null;
        } else {
            u.setLoginname(loginName);
        }
        return userInfoSerivce.find(u);
    }


    @ResponseBody
    @RequestMapping(value = "/sortAndFind/{fileUuid}", method = RequestMethod.GET,produces = "application/json;charset=utf-8")
    public List<UserInfo> sortAndFind(HttpSession s,String loginName, String sort,@PathVariable String fileUuid) {
        UserInfo u = new UserInfo();
        if (loginName == null || loginName == "") {
            u = null;
        } else {
            u.setLoginname(loginName);
        }

        if (sort == null || sort == "") {
            return userInfoSerivce.find(u);
        }
        if (sort.equals("id") || sort.equals("loginname")) {
            return userInfoSerivce.sortAndFind(sort, u);
        }
        return null;
    }


    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public void add(UserInfo u) {//@Valid
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

        Set<ConstraintViolation<UserInfo>> constraintViolations = validator.validate(u);
        StringBuffer buffer = new StringBuffer();
        if (!CollectionUtils.isEmpty(constraintViolations)) {
            Iterator<ConstraintViolation<UserInfo>> iter = constraintViolations.iterator();
            while (iter.hasNext()) {
                String message = iter.next().getMessage();
                buffer.append("[").append(message).append("], ");
            }
        }

        System.out.println(buffer);

        if (u != null)
            userInfoSerivce.add(u);
    }


    /**
     * 获取模和公钥
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getPublicKey", method = RequestMethod.GET)
    public String getPublicKey(HttpSession session) {
        RSAUtils rsa = new RSAUtils();
        //生成公钥和密钥
        Map<String, Object> keyMap = rsa.createKey();
        RSAPublicKey publicKey = (RSAPublicKey) keyMap.get("publicKey");
        RSAPrivateKey privateKey = (RSAPrivateKey) keyMap.get("privateKey");
        //js通过模和公钥指数获取公钥对字符串进行加密，注意必须转为16进制
        //模
        String Modulus = publicKey.getModulus().toString(16);
        //公钥指数
        String Exponent = publicKey.getPublicExponent().toString(16);
        //私钥指数
        String private_exponent = privateKey.getPrivateExponent().toString();
        String s = publicKey.getModulus().toString() + ";" + private_exponent;
        if (session != null) {
            session.setAttribute("11", s);
        }
        String strSet = Modulus + ";" + Exponent;
        return strSet;
    }

    /**
     * 登录
     *
     * @param loginName
     * @param loginPwd
     * @param session
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String loginName, String loginPwd, HttpSession session) {
        try {
            String s = null;
            if (session != null) {
                s = String.valueOf(session.getAttribute("11"));
            }
            RSAUtils rsa = new RSAUtils();
            String Modulus = s.split(";")[0];
            String private_exponent = s.split(";")[1];
            //根据模和私钥指数获取私钥
            RSAPrivateKey prkey = RSAUtils.getPrivateKey(Modulus, private_exponent);
            //解密
            List<UserInfo> userInfos = find(loginName);
            if (userInfos == null || userInfos.isEmpty()) {
                return "user does not exist";
            }
            String password = rsa.decrypttoStr(prkey, loginPwd);
            String encode = DataMask.decode(userInfos.get(0).getPassword());
            System.out.println(password);
            if (encode.equals(password)) {
                return "Login success";
            } else {
                return "Password error";
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "ok";
    }

}
